package com.pliu.sqlSession;

import com.pliu.config.BoundSql;
import com.pliu.pojo.Configuration;
import com.pliu.pojo.MappedStatement;
import com.pliu.utils.GenericTokenParser;
import com.pliu.utils.ParameterMapping;
import com.pliu.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName SimpleExecutor
 * @Description 执行jdbc代码的类
 * @Author pliu
 * @Date 2020/6/21 16:34
 * @Version 1.0
 **/
public class SimpleExecutor implements Executor {

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //1.注册驱动,获取数据库连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取sql语句
        String sql = mappedStatement.getSql();
        //2.5. 转换sql语句
        BoundSql boundSql = getBoundSql(sql);
        //3.获取预处理对象prepareStatement
        PreparedStatement statement = connection.prepareStatement(boundSql.getSqlText());
        //4.设置参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);
        if (null != paramterTypeClass) {//如果参数类型不为空,设置参数
            List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                String content = parameterMapping.getContent();
                //反射
                Field field = paramterTypeClass.getDeclaredField(content);
                field.setAccessible(true);//暴力访问私有变量
                Object o = field.get(params[0]);
                statement.setObject(i+1,o);
            }
        }
        //5.执行sql
        ResultSet resultSet = statement.executeQuery();
        //6.封装返回结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        List rtnList = new ArrayList();
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);//字段名
                Object value = resultSet.getObject(columnName);//字段值
                //使用反射或者内省,根据数据库表和实体的对应关系,完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);
            }
            rtnList.add(o);
        }

        return rtnList;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //1.注册驱动,获取数据库连接
            connection = configuration.getDataSource().getConnection();
            //2.获取sql语句
            String sql = mappedStatement.getSql();
            //2.5. 转换sql语句
            BoundSql boundSql = getBoundSql(sql);
            //3.获取预处理对象prepareStatement
            statement = connection.prepareStatement(boundSql.getSqlText());
            //4.设置参数
            String paramterType = mappedStatement.getParamterType();
            Class<?> paramterTypeClass = getClassType(paramterType);
            if (null != paramterTypeClass) {//如果参数类型不为空,设置参数
                List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
                for (int i = 0; i < parameterMappings.size(); i++) {
                    ParameterMapping parameterMapping = parameterMappings.get(i);
                    String content = parameterMapping.getContent();
                    //反射
                    Field field = paramterTypeClass.getDeclaredField(content);
                    field.setAccessible(true);//暴力访问私有变量
                    Object o = field.get(params[0]);
                    statement.setObject(i+1,o);
                }
            }
            //5.执行sql
            int updateCount = statement.executeUpdate();
            //6.返回结果
            return updateCount;
        } catch (Exception e) {
            System.err.println(e.toString());
        } finally {
            try {
                if (null != statement)
                statement.close();
            } catch (Exception e) {
                System.err.println(e.toString());
            }

            try {
                if (null != connection)
                    connection.close();
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        return 0;
    }

    private Class<?> getClassType(String paramterType) throws Exception {
        if (null != paramterType && !paramterType.isEmpty()) {
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", handler);
        String parseSql = genericTokenParser.parse(sql);

        BoundSql boundSql = new BoundSql(parseSql);
        boundSql.setParameterMappings(handler.getParameterMappings());
        return boundSql;
    }
}
